package cn.zwxky.android.user.News;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.LsfbFragment;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.view.banner.LsfbBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.zwxky.android.user.R;
import cn.zwxky.android.user.Utils.ListViewForScrollView;
import cn.zwxky.android.user.Utils.LittleUtils;
import cn.zwxky.android.user.Utils.Permission;
import cn.zwxky.android.user.Utils.URLString;
import cn.zwxky.android.user.Utils.WebActivity;


/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class NewsFragment extends LsfbFragment {


    /**
     * view 对象
     */
    private View view;

    /**
     * activity对象
     */
    private Activity mactivity;

    @ViewInject(R.id.tv_badg)
    private TextView tv_badg;

    @ViewInject(R.id.banner)
    private LsfbBanner banner;

    @ViewInject(R.id.btn_goto)
    private TextView btn_goto;

    private List<BannerBean.ListBean> bannerList;

    private boolean isload = false;

    /**
     * list列表
     */
    @ViewInject(R.id.fg_news_list)
    private ListViewForScrollView news_list;

    @ViewInject(R.id.refershlayout)
    private PullToRefreshScrollView refreshScrollView;

    @ViewInject(R.id.fg_news_banner)
    private RelativeLayout fg_news_banner;

    private List<NewsBean.ListBean> mList;
    private NewsAdapter adapter;

    private int page = 0;
    private Information info;

    private int type=0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_news, null);
        ViewInjectUtils.inject(this, view);
        LsfbEvent.getInstantiation().register2(this);
        Permission permission = new Permission(mactivity);
        permission.GetMeshPermission();
        permission.GetAddressBookPermission();
        permission.GetLocationPermission2();

        mList = new ArrayList<>();
        adapter = new NewsAdapter(mactivity, R.layout.item_news, mList);
        news_list.setAdapter(adapter);

        refreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        refreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                isload = true;
                page = 0;
                getData();
                type=1;
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                page++;
                isload = false;
                getData();
                type=1;
            }
        });

        bannerList = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils.dp2px(mactivity, 20), DensityUtils.dp2px(mactivity, 20));
        banner.setPointLayout(layoutParams);
        banner.setPoint(R.mipmap.iv_display, R.mipmap.iv_hide);
//        banner.setNavHorizontalGravity(Gravity.CENTER_HORIZONTAL);
        info = new Information();

//        if (LittleUtils.badg.isEmpty() || LittleUtils.badg.equals("0")){
//            tv_badg.setVisibility(View.GONE);
//        }else {
//            tv_badg.setVisibility(View.VISIBLE);
//            tv_badg.setText(LittleUtils.badg);
//        }

        isload = true;
        page = 0;
        getData();
        type=0;
        getBeanner();

        return view;
    }

    /**
     * 用于存储activity对象
     *
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mactivity = activity;
    }


    @Override
    public void onStart() {
        super.onStart();
        //获取未读消息数并显示
        String unreadNum = SobotApi.getUnreadMsg(mactivity.getApplicationContext()) > 0 ?
                SobotApi.getUnreadMsg(mactivity.getApplicationContext()) + "" : "";
        LsfbLog.e("获取未读消息数并显示"+unreadNum);
        if (unreadNum.isEmpty()){
            tv_badg.setVisibility(View.GONE);
        }else {
            tv_badg.setVisibility(View.VISIBLE);
            tv_badg.setText(unreadNum);
        }
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.fg_msg})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fg_msg:
                info.setAppkey("a14627c9117f47da9ab858fc55083aef");
                info.setUid(Config.getUserId());
                info.setUname(LittleUtils.nikename);
                info.setFace(LittleUtils.img_head);
                info.setTel(LittleUtils.phone);
                info.setColor("#374164");
                SobotApi.startSobotChat(mactivity, info);
                break;
        }
    }


    @Override
    protected void Resume() {
        isload = true;
        page = 0;
        getData();
        getBeanner();
        type=0;
        //获取未读消息数并显示
        String unreadNum = SobotApi.getUnreadMsg(mactivity.getApplicationContext()) > 0 ?
                SobotApi.getUnreadMsg(mactivity.getApplicationContext()) + "" : "";
        LsfbLog.e("获取未读消息数并显示"+unreadNum);
        if (unreadNum.isEmpty()){
            tv_badg.setVisibility(View.GONE);
        }else {
            tv_badg.setVisibility(View.VISIBLE);
            tv_badg.setText(unreadNum);
        }
    }

    @Override
    public void initData() {

    }

    public void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        hashMap.put("num", "10");
        hashMap.put("page", String.valueOf(page));
        new BaseInternet().getData_Get(URLString.NEWSLIST, hashMap, NewsBean.class, new NewsEvent<NewsBean>(), true, true);
    }

    @EventAnnotation
    public void NewsEvent(NewsEvent<NewsBean> event) {
        refreshScrollView.onRefreshComplete();
        switch (event.getCode()) {
            case 200:
                if (isload) {
                    mList.clear();
                }
                mList.addAll(event.getData().getList());
                adapter.notifyDataSetChanged();
                break;
            default:
                if (isload) {
                    mList.clear();
                    if (type==1) {
                        SN.SnackShow(news_list, event.getMsg());
                    }
                } else {
                    page--;
                    SN.SnackShow(news_list,"没有更多数据");
                }
                break;
        }
    }

    /**
     * 获取banner图
     */
    public void getBeanner() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("uid",Config.getUserId());
        new BaseInternet().getData_Get(URLString.NEWSBANNER, hashMap, BannerBean.class, new BannerEvent<BannerBean>(), true, true);
    }

    @EventAnnotation
    public void BannerEvent(BannerEvent<BannerBean> event) {
        switch (event.getCode()) {
            case 200:
                fg_news_banner.setVisibility(View.VISIBLE);
                bannerList.clear();
                bannerList.addAll(event.getData().getList());
                initBanner();
                break;
            default:
                fg_news_banner.setVisibility(View.GONE);
                break;
        }
    }

    public void initBanner() {

        LittleUtils.initBanner(banner, bannerList, mactivity, new LsfbBanner.BannerOnItemClickLister() {
            @Override
            public void onClick(int i) {
                startActivity(new Intent(mactivity, WebActivity.class).putExtra("url", URLString.WED_URL+bannerList.get(i).getUrl()).putExtra("title","查看全文"));
            }
        });
    }

    @EventAnnotation
    public void NewsClickEvent(NewsClickEvent event){
        startActivity(new Intent(mactivity, WebActivity.class).putExtra("url", URLString.WED_URL+event.getData()).putExtra("title","查看全文"));
    }

    @Override
    public void onDestroy() {
        LsfbEvent.getInstantiation().unregister2(this);
        super.onDestroy();
    }

}
